#include <stdio.h>
#include <stdlib.h>
struct node
{//链表结点类型，包含一个存放整型数据的 data 成员，和一个指向下一个结点的next成员
    int data ;
    struct node *next ;   
};

//第一关代码
struct node *createRlist()
{//函数功能：创建一个有一个空循环链表，返回值为头指针
  struct node * head = (struct node *)malloc(sizeof(struct node *));
  if (NULL == head)
      return NULL;
  head->data = 0;
  head->next = head;
  return head;
}


void insertOrder(struct node *list, int insData)
{
 //在单向递增有序的循环链表（表头指针list）中插入数据元素insData，使之依然有序 。
    struct node * new_node = (struct node *)malloc(sizeof(struct node));
    if (NULL == new_node)
        return;
    struct node * p = NULL;
    for (p = list; p->next != list && p->next->data < insData; p = p->next);
    new_node->next = p->next;
    p->next = new_node;
    new_node->data = insData;
}

int deleteData(struct node  *list, int delData)
{
    //在单向递增有序循环链表（表头指针list）中删除所有值为delData的结点,返回值为删除结点的个数
    int count = 0;
    struct node * delNode = NULL;
    for (struct node * pre = list, * post = list->next; post != list; post = pre->next) {
        if(post->data == delData) {
            delNode = post;
            pre->next = post->next;
            free(delNode);
            delNode = NULL;
            count++;
        } else {
            pre = pre->next;
        }
    }
    return count;
}

void printRlist(struct node *list)
{
 //从链表第一个结点开始输出单向循环链表中各数据元素的值，每输出一个数据元素换一行
    for (struct node * p = list->next; p != list; p = p->next) {
        printf("%d ", p->data);
    }
}

int destroyRlist(struct node *list)
{
    //从第一个结点开始释放循环链表各结点占用的空间,返回值为最后一个结点的值
    struct node * pre = NULL;
    struct node * post = NULL;
    int finalData = 0;
    for (pre = post = list->next; pre->next != list; pre = post) {
        post = pre->next;
        free(pre);
        pre = NULL;
    }
    finalData = pre->data;
    free(pre);
    pre = post = NULL;
    free(list);
    return finalData;
}
